package com.xbongbong.callback.service.imp;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.callback.service.ConnectorProducerService;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.pro.connector.pojo.dto.ConnectorHistoryDataInitDTO;
import com.xbongbong.pro.connector.pojo.dto.ConnectorRabbitMqDTO;
import com.xbongbong.pro.constant.RaidersConstant;
import com.xbongbong.pro.rabbitmq.producer.ConnectorProducer;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 连接器
 * 创建时间 2020/12/15 11:04 AM
 * 修改时间 2020/12/15 11:04 AM
 * @author chy
 */
@Service("connectorProducerService")
public class ConnectorProducerServiceImpl implements ConnectorProducerService {
    private static final Logger LOG = LoggerFactory.getLogger(ConnectorProducerServiceImpl.class);

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private ConnectorProducer connectorProducer;

    @Override
    public void triggerSend(String corpid, XbbRefTypeEnum xbbRefTypeEnum, String operate, Long dataId) throws XbbException {
        triggerSend(corpid, xbbRefTypeEnum, operate, Arrays.asList(dataId));
    }

    @Override
    public void triggerSend(String corpid, XbbRefTypeEnum xbbRefTypeEnum, String operate, List<Long> dataIdList) throws XbbException {
        List<XbbRefTypeEnum> xbbRefTypeEnums = Arrays.asList(XbbRefTypeEnum.CUSTOMER, XbbRefTypeEnum.CONTRACT,
                XbbRefTypeEnum.PRODUCT, XbbRefTypeEnum.PRODUCT_CATEGORY, XbbRefTypeEnum.WAREHOUSE,
                XbbRefTypeEnum.PAYMENT, XbbRefTypeEnum.PAYMENT_SHEET, XbbRefTypeEnum.CONTACT, XbbRefTypeEnum.SALES_OPPORTUNITY);
        LOG.info("connectorProducerService triggerSend sendMessage");
        if (!xbbRefTypeEnums.contains(xbbRefTypeEnum)) {
            return;
        }
        ConnectorRabbitMqDTO connectorRabbitMqDTO = new ConnectorRabbitMqDTO();
        connectorRabbitMqDTO.setCorpid(corpid);
        connectorRabbitMqDTO.setXbbRefTypeEnum(xbbRefTypeEnum);
        connectorRabbitMqDTO.setOperate(operate);
        connectorRabbitMqDTO.setDataIdList(dataIdList);
        connectorProducer.sendMessage(connectorRabbitMqDTO);
    }

    @Override
    public void historyDataInit(String corpid) throws XbbException {
        ConnectorHistoryDataInitDTO connectorHistoryDataInitDTO = new ConnectorHistoryDataInitDTO();
        connectorHistoryDataInitDTO.setCorpid(corpid);
        connectorHistoryDataInitDTO.setTotalNum(100);
        connectorProducer.sendMessage(connectorHistoryDataInitDTO);
    }

    /**
     * 校验公司的corpid是否在白名单中
     * 返回的whiteSet中有*，代表匹配任意一个，即不限制，匹配上corpid的也不限制
     * @param corpid
     * @return
     */
    public boolean checkWhite(String corpid) {
        Set<String> whiteSet = getConnectorWhiteList();
        return whiteSet.contains(corpid) || whiteSet.contains("*");
    }

    /**
     * 获取白名单
     * @return
     * 创建时间 2020/12/25 2:45 PM
     * 修改时间 2020/12/25 2:45 PM
     * @author chy
     */
    private Set<String> getConnectorWhiteList() {
        Set<String> whiteSet = new HashSet<>();
        String alias = CompanyConfigEnum.CONNECTOR_WHITE.getAlias();
        String value = paasRedisHelper.getValue(RedisConstant.KEY_COMPANY_CONFIG, alias);
        if (value == null) {
            //读出白名单配置
            CompanyConfigEntity companyConfig = companyConfigModel.getByConfigAlias(alias, RaidersConstant.RAIDERS_WHITE_CORPID);
            //若为*，不限制，全部发（数据库del=1或者companyConfig中的configValue包含*都为不限制）
            String configValue = "[\"*\"]";
            if (companyConfig != null) {
                configValue = companyConfig.getConfigValue();
            }

            List<String> whiteList = new ArrayList<>();
            try {
                whiteList = JsonHelperUtil.parseArray(configValue, String.class);
            } catch (Exception e) {
                LOG.error("companyConfig中的configValue异常");
            }
            whiteSet.addAll(whiteList);
            //存入缓存
            paasRedisHelper.setValue(RedisConstant.KEY_COMPANY_CONFIG, alias, JSONArray.toJSONString(whiteSet), TimeConstant.TINY_DURATION);
        } else {
            whiteSet.addAll(JsonHelperUtil.parseArray(value, String.class));
        }
        return whiteSet;
    }

}
